package com.app.teaware.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.app.teaware.R;
import com.app.teaware.basis.Constants;
import com.app.teaware.bean.BaseInfoUpdateCache;
import com.app.teaware.bean.BoxInfoListBean;
import com.app.teaware.bean.CompanyListBean;
import com.app.teaware.bean.CraftListBean;
import com.app.teaware.bean.GoodsListBean;
import com.app.teaware.bean.GoodsListData;
import com.app.teaware.bean.LocationListBean;
import com.app.teaware.bean.LoginBean;
import com.app.teaware.bean.MenuBean;
import com.app.teaware.bean.SpeciesListBean;
import com.app.teaware.bean.TrayInfoListBean;
import com.app.teaware.bean.UnitListBean;
import com.app.teaware.bean.UnitWholeListBean;
import com.app.teaware.greendao.GreenDaoUtils;
import com.app.teaware.util.MyUtils;
import com.flyco.dialog.widget.NormalDialog;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.qmuiteam.qmui.widget.QMUIProgressBar;

import org.greenrobot.eventbus.EventBus;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import my.DialogUtils;
import my.LogUtil;
import my.StringUtil;
import my.TimeUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;


/**
 * @作者 fourfaith
 * @备注 新闻详情图片查看activity发、
 */
public class UpdateBaseInfoDialog extends NormalDialog {

	public static void toBaseInfoUpdateDialog(Activity mContext,BaseInfoUpdateCache updateInfo){
	    if(updateInfo == null){
	        updateInfo = new BaseInfoUpdateCache();
            updateInfo.setForceUpdate(true);
        }
		new UpdateBaseInfoDialog(mContext,updateInfo).show();
	}

//	public static void toBaseInfoUpdateDialog(Activity mContext){
//		new UpdateBaseInfoDialog(mContext).show();
//	}



	@BindView(R.id.progress_bar)
	QMUIProgressBar progress_bar;
	@BindView(R.id.text_message)
	TextView text_message;
	@BindView(R.id.text_percent)
	TextView text_percent;
	@BindView(R.id.text_total_current)
	TextView text_total_current;
	Activity mContext;

	int updatedCount = 0;
	int current_total = 100;
	String currentUpdate;

	BaseInfoUpdateCache updateInfo;


	public UpdateBaseInfoDialog(Activity context,BaseInfoUpdateCache dateInfo) {
		super(context);
		mContext = context;
		updateInfo = dateInfo;
		setCancelable(false);
		setCanceledOnTouchOutside(false);
	}

	@Override
	public View onCreateView() {
//        return super.onCreateView();
		View inflate = LayoutInflater.from(mContext).inflate(R.layout.user_update_baseinfo_dialog, null);
		ButterKnife.bind(this, inflate);
		widthScale(0.8f);
		return inflate;
	}

	@Override
	public void setUiBeforShow() {
		initViews();
		initData();
	}

	private void initViews() {

	}

	private void initData() {
//		updateInfoOld = UserBaseInfoUpdateCache.getFromCache();
		updateBaseInfoData();
	}

	@SuppressLint("StaticFieldLeak")
	public  void updateBaseInfoData() {
		new AsyncTask<String, Integer, String>() {
			@Override
			protected String doInBackground(String... strings) {

				if (updateInfo.isNeedUpdateUnit()) {
					currentUpdate = "正在下载单位信息基础数据";
					updatedCount = 0;
					current_total = updateInfo.getUnitCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_UNIT);
				}


				if (updateInfo.isNeedUpdateUnitWhole()) {
					currentUpdate = "正在下载整件单位信息基础数据";
					updatedCount = 0;
					current_total = updateInfo.getUnitWholeCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_WHOLE_UNIT);
				}

				if (updateInfo.isNeedUpdateBox()) {
					currentUpdate = "正在下载纸箱基础数据";
					updatedCount = 0;
					current_total = updateInfo.getBoxCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_BOX);
				}

				if (updateInfo.isNeedUpdateTray()) {
					currentUpdate = "正在下载托盘基础数据";
					updatedCount = 0;
					current_total = updateInfo.getTrayCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_TRAY);
				}

				if (updateInfo.isNeedUpdateCustomer()) {
					currentUpdate = "正在下载客户基础数据";
					updatedCount = 0;
					current_total = updateInfo.getCustomerCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_CUSTOMER);
				}

				if (updateInfo.isNeedUpdateCraft()) {
					currentUpdate = "正在下载工艺基础数据";
					updatedCount = 0;
					current_total = updateInfo.getCraftCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_CRAFT);
				}

				if (updateInfo.isNeedUpdateGoods()) {
					currentUpdate = "正在下载货品基础数据";
					updatedCount = 0;
					current_total = updateInfo.getGoodsCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_GOODS);
				}

				if (updateInfo.isNeedUpdateLocation()) {
					currentUpdate = "正在下载仓库数据";
					updatedCount = 0;
					current_total = updateInfo.getLocationCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_LOCATION);
				}

				if (updateInfo.isNeedUpdateSpecies()) {
					currentUpdate = "正在下载货品分类数据";
					updatedCount = 0;
					current_total = updateInfo.getSpeciesCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_SPECIES);
				}

				LogUtil.i("同步本地信息结束");
				return null;
			}

			@Override
			protected void onPostExecute(String s) {
				super.onPostExecute(s);
//				updateInfo.setLastCacheUpdateTime(new Date().getTime());
				updateInfo.save();
				currentUpdate = "下载信息完成";
				mHandler.sendEmptyMessage(MESSAGE_UPDATED_FINISH);
			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}
		}.execute("");

	}

	public void getList(String type) {
		MyParams params = null;
		switch (type) {
			case GreenDaoUtils.TYPE_UNIT:
				params = new MyParams();
				params.put("aid", LoginBean.getInstance().getAcode());
				params.put("dna", "单位");
				MyHttpUtils.getExcute(Constants.URL_DSUB_SELECT_ALL, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								UnitListBean unitListBean = (UnitListBean) result;
								GreenDaoUtils.unitBeanInsertData(unitListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,unitListBean.getList().size());
							}
							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, UnitListBean.class);
				break;

			case GreenDaoUtils.TYPE_WHOLE_UNIT:
				params = new MyParams();
				params.put("aid", LoginBean.getInstance().getAcode());
				params.put("dna", "整件单位");
				MyHttpUtils.getExcute(Constants.URL_DSUB_SELECT_ALL, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								UnitWholeListBean unitListBean = (UnitWholeListBean) result;
								GreenDaoUtils.unitWholeBeanInsertData(unitListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,unitListBean.getList().size());
							}
							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, UnitWholeListBean.class);
				break;

			case GreenDaoUtils.TYPE_TRAY:
				//ice 1 获取包装信息，如纸箱重量和托盘重量
				params = new MyParams();
				params.put("aid", LoginBean.getInstance().getAcode());
				params.put("bfs", "托盘");
				MyHttpUtils.getExcute(Constants.URL_BOXINFO_SELECT_BY_FSG, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								TrayInfoListBean trayInfoListBean = (TrayInfoListBean) result;
								GreenDaoUtils.trayBeanInsertData(trayInfoListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,trayInfoListBean .getList().size());
							}
							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, TrayInfoListBean.class);
				break;
			case GreenDaoUtils.TYPE_BOX:
				//ice 2 纸箱
				params = new MyParams();
				params.put("aid", LoginBean.getInstance().getAcode());
				params.put("bfs", "纸箱");
				MyHttpUtils.getExcute(Constants.URL_BOXINFO_SELECT_BY_FSG, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								BoxInfoListBean boxInfoListBean = (BoxInfoListBean) result;
								GreenDaoUtils.boxBeanInsertData(boxInfoListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,boxInfoListBean.getList().size());
							}


							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, BoxInfoListBean.class);
				break;
			case GreenDaoUtils.TYPE_CUSTOMER:
				//客户
				params = new MyParams();
				params.put("aid", LoginBean.getInstance().getAcode());
				params.put("cfsign", "1");
				MyHttpUtils.getExcute(Constants.URL_COMPANY_SELECT_ALL, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								CompanyListBean customerListBean = (CompanyListBean) result;
								GreenDaoUtils.customerBeanInsertData(customerListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,customerListBean.getList().size());
							}


							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, CompanyListBean.class);
				break;
			case GreenDaoUtils.TYPE_CRAFT:
				//工艺
				params = new MyParams();
				params.put("aid", LoginBean.getInstance().getAcode());
				MyHttpUtils.getExcute(Constants.URL_CRAFT_SELECT_ALL, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								CraftListBean craftListBean = (CraftListBean) result;
								GreenDaoUtils.craftBeanInsertData(craftListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,craftListBean.getList().size());
							}


							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, CraftListBean.class);
				break;
			case GreenDaoUtils.TYPE_GOODS:
				//货品资料
				params = new MyParams();
				params.put("aid", LoginBean.getInstance().getAcode());
				MyHttpUtils.getExcute(Constants.URL_GOODS_SELECT_ALL_BY_AID, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								GoodsListBean goodsListBean = (GoodsListBean) result;
								GreenDaoUtils.goodsBeanInsertData(goodsListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,goodsListBean.getList().size());
							}


							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, GoodsListBean.class);
				break;
			case GreenDaoUtils.TYPE_LOCATION:
				//楼层
				params = new MyParams();
				params.put("aid", LoginBean.getInstance().getAcode());
				params.put("dna", "仓库");
				MyHttpUtils.getExcute(Constants.URL_DSUB_SELECT_ALL, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								LocationListBean locationListBean = (LocationListBean) result;
								GreenDaoUtils.locationBeanInsertData(locationListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,locationListBean.getList().size());
							}
							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, LocationListBean.class);
				break;
			case GreenDaoUtils.TYPE_SPECIES:
				//货品分类
				params = new MyParams();
				params.put("aid", LoginBean.getInstance().getAcode());
				MyHttpUtils.getExcute(Constants.URL_SPECIES_SELECT_ALL, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								SpeciesListBean speciesListBean = (SpeciesListBean) result;
								GreenDaoUtils.speciesBeanInsertData(speciesListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,speciesListBean.getList().size());
							}
							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, SpeciesListBean.class);
				break;
		}
	}

	GreenDaoUtils.GreenDaoInserCallBack mCallBack = new GreenDaoUtils.GreenDaoInserCallBack() {
		@Override
		public void onDataInsert(int count) {
//			updatedCount++;
			updatedCount+= count;
			mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
		}
	};

	public static final int MESSAGE_UPDATED_COUNT = 11;
	public static final int MESSAGE_UPDATED_FINISH = 12;
	public static final int MESSAGE_CONTACT_FAKE_PROGRESS = 13;
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what){
				case MESSAGE_UPDATED_COUNT:
					updateProgressView();
					break;
				case MESSAGE_UPDATED_FINISH:
					StringBuilder builder = new StringBuilder();
					if(updateInfo.isUpdateSuccess()){
						if(updateInfo.isNeedUpdateUnit()){
							builder.append("重量单位信息共更新了").append(updateInfo.getUnitCountUpdated()).append("条 \n");
						}
						if(updateInfo.isNeedUpdateUnitWhole()){
							builder.append("整件单位信息共更新了").append(updateInfo.getUnitWholeCountUpdated()).append("条 \n");
						}
						if(updateInfo.isNeedUpdateBox()){
							builder.append("纸箱信息共更新了").append(updateInfo.getBoxCountUpdated()).append("条 \n");
						}
						if(updateInfo.isNeedUpdateTray()){
							builder.append("托盘信息共更新了").append(updateInfo.getTrayCountUpdated()).append("条\n ");
						}
						if(updateInfo.isNeedUpdateCustomer()){
							builder.append("客户信息共更新了").append(updateInfo.getCustomerCountUpdated()).append("条\n");
						}
						if(updateInfo.isNeedUpdateCraft()){
							builder.append("工艺信息共更新了").append(updateInfo.getCraftCountUpdated()).append("条\n");
						}
						if(updateInfo.isNeedUpdateCraft()){
							builder.append("货品资料信息共更新了").append(updateInfo.getGoodsCountUpdated()).append("条\n");
						}
						if(updateInfo.isNeedUpdateLocation()){
							builder.append("楼层资料信息共更新了").append(updateInfo.getLocationCountUpdated()).append("条\n");
						}
						if(updateInfo.isNeedUpdateSpecies()){
							builder.append("货品分类共更新了").append(updateInfo.getSpeciesCountUpdated()).append("条\n");
						}

						EventBus.getDefault().post(new GreenDaoUtils.EventDateChange(GreenDaoUtils.EventDateChange.TYPE_ALL));
					}else {
						builder.append("更新失败");
					}
					DialogUtils.DialogOkMsg(mContext,builder.toString());
					dismiss();
					break;
				case MESSAGE_CONTACT_FAKE_PROGRESS:
					if(mContext == null || mContext.isFinishing())return;
					if(TextUtils.isEmpty(currentUpdate))return;
					if(!currentUpdate.equals("正在下载通讯录基础数据"))return;
					if(updatedCount >= (current_total-10) )return;
						updateProgressView();
					updatedCount += 10;
					mHandler.sendEmptyMessageDelayed(MESSAGE_CONTACT_FAKE_PROGRESS,2000);
					break;
			}

		}
	};



	void updateProgressView(){
//		LogUtil.i("updateProgressView------updatedCount-->"+updatedCount);
//		LogUtil.i("updateProgressView---current_total-->"+current_total);
		if(current_total == 0){
			current_total = 20000;
		}else {

			if(updatedCount >= current_total){
				updatedCount = current_total-1;
			}
		}
		progress_bar.setMaxValue(current_total);
		boolean animated = updatedCount > progress_bar.getProgress();
		progress_bar.setProgress(updatedCount,animated);
		text_message.setText(currentUpdate);
		text_total_current.setText(updatedCount+"/"+current_total);
		text_percent.setText(StringUtil.getPercent(updatedCount,current_total));
	}

}
